package cn.tedu.eshihui.security;


import cn.tedu.eshihui.mapper.AdminMapper;
import cn.tedu.eshihui.pojo.vo.AdminLoginInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private AdminMapper adminMapper;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        log.debug("Spring Security调用了loadUserByUsername()方法，参数：{}", s);
        AdminLoginInfoVo adminLoginInfoVo= adminMapper.getLoginInfoByUsername(s);
        log.debug("从数据库查询用户名【{}】匹配的信息，结果：{}", s, adminLoginInfoVo);
        if (adminLoginInfoVo==null){
            String message="查无此人";
            log.debug(message);
            return null;
        }
        List<String> permissions= adminLoginInfoVo.getPermissionValues();
        List<SimpleGrantedAuthority> authorities=new ArrayList<>();
        for (String permission:permissions) {
            SimpleGrantedAuthority authority=new SimpleGrantedAuthority(permission);
            authorities.add(authority);
        }


            AdminDetails adminDetails=new AdminDetails(
                    adminLoginInfoVo.getId(),
                    adminLoginInfoVo.getUsername(),
                    adminLoginInfoVo.getPassword(),
                    adminLoginInfoVo.getEnable()==1,
                    authorities);
        log.debug("即将向Spring Security返回UserDetails对象：{}", adminDetails);
            return adminDetails;

    }
}
